// 处理本地存储的工具函数
function setItemWithExpiry(key, value, ttl) {
    const item = {
        value: value,
        expiry: new Date().getTime() + ttl,
    };
    localStorage.setItem(key, JSON.stringify(item));
}

function getItemWithExpiry(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) {
        return null;
    }
    const item = JSON.parse(itemStr);
    const now = new Date();
    if (now.getTime() > item.expiry) {
        localStorage.removeItem(key);
        return null;
    }
    return item.value;
}

// 获取用户ID
const userId = getItemWithExpiry('userId');

document.addEventListener('DOMContentLoaded', function() {
    // 检查用户是否登录
    if (!userId) {
        window.location.href = '/login.html';
        return;
    }
    
    // 初始化日历
    initCalendar();
    
    // 初始化表单提交
    initBookingForm();
});

// 日历功能
function initCalendar() {
    const calendarGrid = document.querySelector('.calendar-grid');
    const calendarTitle = document.querySelector('.calendar-title');
    const prevButton = document.querySelector('.calendar-nav.prev');
    const nextButton = document.querySelector('.calendar-nav.next');
    
    let currentDate = new Date();
    
    // 更新日历显示
    function updateCalendar() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1; // 转换为1-12的月份
        
        console.log('更新日历:', {year, month});
        
        // 更新标题
        calendarTitle.textContent = `${year}年${month}月`;
        
        // 清空日历网格
        calendarGrid.innerHTML = '';
        
        // 添加星期标题
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        weekdays.forEach(day => {
            const dayElement = document.createElement('div');
            dayElement.className = 'calendar-day weekday';
            dayElement.textContent = day;
            calendarGrid.appendChild(dayElement);
        });
        
        // 获取当月第一天
        const firstDay = new Date(year, month - 1, 1); // 转回0-11的月份
        // 获取当月最后一天
        const lastDay = new Date(year, month, 0); // 转回0-11的月份
        
        // 添加空白格子
        for (let i = 0; i < firstDay.getDay(); i++) {
            const emptyDay = document.createElement('div');
            emptyDay.className = 'calendar-day empty';
            calendarGrid.appendChild(emptyDay);
        }
        
        // 添加日期
        for (let day = 1; day <= lastDay.getDate(); day++) {
            const dayElement = document.createElement('div');
            dayElement.className = 'calendar-day';
            dayElement.textContent = day;
            
            // 检查是否有活动
            if (hasEvent(year, month, day)) {
                console.log('添加高亮:', {year, month, day});
                dayElement.classList.add('has-event');
                dayElement.classList.add('unavailable');
                dayElement.title = '已满';
            }
            
            calendarGrid.appendChild(dayElement);
        }
    }
    
    // 检查日期是否有活动
    function hasEvent(year, month, day) {
        // 从全局变量中获取活动数据
        console.log('检查日期:', {year, month, day});
        console.log('当前活动数据:', window.calendarEvents);
        
        if (!window.calendarEvents) return false;
        
        const hasEvent = window.calendarEvents.some(event => {
            const match = event.year === year && 
                         event.month === month && 
                         event.day === day;
            if (match) {
                console.log('找到匹配的日期:', event);
            }
            return match;
        });
        
        console.log('是否有活动:', hasEvent);
        return hasEvent;
    }
    
    // 获取日历数据
    async function fetchCalendarEvents() {
        try {
            // 获取当前年月
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1; // 月份从1开始
            
            console.log('获取日历数据:', {year, month});
            
            // 构建查询参数
            const params = new URLSearchParams({
                year: year,
                month: month
            });
            
            const response = await fetch(`http://localhost:8080/culture/calendar?${params}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'userId': userId
                }
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('错误响应:', errorText);
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }
            
            // 获取响应文本
            const responseText = await response.text();
            console.log('原始响应:', responseText);
            
            // 尝试解析JSON
            let responseData;
            try {
                responseData = JSON.parse(responseText);
            } catch (parseError) {
                console.error('JSON解析错误:', parseError);
                throw new Error('服务器返回的数据格式不正确');
            }
            
            // 检查响应格式
            if (!responseData || responseData.code !== 200 || !Array.isArray(responseData.data)) {
                console.error('数据格式错误:', responseData);
                throw new Error('日历数据格式不正确');
            }
            
            // 将数据存储在全局变量中
            window.calendarEvents = responseData.data;
            console.log('设置日历数据:', window.calendarEvents);
            
            // 更新日历显示
            updateCalendar();
        } catch (error) {
            console.error('获取日历数据失败:', error);
            // 显示错误信息给用户
            const calendarGrid = document.querySelector('.calendar-grid');
            if (calendarGrid) {
                calendarGrid.innerHTML = `
                    <div class="error-message" style="grid-column: 1 / -1; text-align: center; padding: 20px; color: #e74c3c;">
                        <p>获取日历数据失败</p>
                        <p style="font-size: 0.9em; color: #666;">${error.message}</p>
                        <button onclick="fetchCalendarEvents()" style="margin-top: 10px; padding: 5px 15px; background: #e74c3c; color: white; border: none; border-radius: 4px; cursor: pointer;">
                            重试
                        </button>
                    </div>
                `;
            }
        }
    }
    
    // 上个月
    prevButton.addEventListener('click', async () => {
        currentDate.setMonth(currentDate.getMonth() - 1);
        // 先获取数据，再更新显示
        await fetchCalendarEvents();
    });
    
    // 下个月
    nextButton.addEventListener('click', async () => {
        currentDate.setMonth(currentDate.getMonth() + 1);
        // 先获取数据，再更新显示
        await fetchCalendarEvents();
    });
    
    // 初始化显示
    updateCalendar();
    // 获取日历数据
    fetchCalendarEvents();
}

// 预约表单功能
function initBookingForm() {
    const bookingForm = document.querySelector('.booking-form');
    
    if (bookingForm) {
        bookingForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const formData = {
                username: document.getElementById('name').value,
                phone: document.getElementById('phone').value,
                email: document.getElementById('email').value,
                activity: document.getElementById('activity').value,
                date: document.getElementById('date').value,
                message: document.getElementById('message').value
            };
            
            // 这里可以添加表单验证
            if (!validateForm(formData)) {
                return;
            }
            
            // 模拟表单提交
            submitBooking(formData);
        });
    }
}

// 表单验证
function validateForm(data) {
    // 验证姓名
    if (!data.username || !data.username.trim()) {
        alert('请输入姓名');
        return false;
    }
    
    // 验证电话
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!data.phone || !phoneRegex.test(data.phone.trim())) {
        alert('请输入正确的手机号码');
        return false;
    }
    
    // 验证邮箱
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!data.email || !emailRegex.test(data.email.trim())) {
        alert('请输入正确的邮箱地址');
        return false;
    }
    
    // 验证活动选择
    if (!data.activity) {
        alert('请选择活动项目');
        return false;
    }
    
    // 验证日期
    if (!data.date) {
        alert('请选择预约日期');
        return false;
    }

    // 验证日期不能是今天之前的
    const selectedDate = new Date(data.date);
    const today = new Date();
    // 设置时间为当天的0点0分0秒
    today.setHours(0, 0, 0, 0);
    
    if (selectedDate < today) {
        alert('不能预约今天之前的活动');
        return false;
    }
    
    return true;
}

// 提交预约
function submitBooking(data) {
    // 构建完整的预约信息
    const bookingInfo = {
        username: data.username.trim(),
        phone: data.phone.trim(),
        email: data.email.trim(),
        activity: data.activity,
        date: formatDate(data.date),
        message: data.message ? data.message.trim() : '',
        status: 'pending',
        createTime: formatDateTime(new Date())
    };

    // 检查用户是否已登录
    const userId = getItemWithExpiry('userId');
    if (!userId) {
        alert('请先登录后再进行预订');
        window.location.href = 'login.html';
        return;
    }

    // 详细验证所有字段
    const validationErrors = [];
    
    if (!bookingInfo.username) {
        validationErrors.push('请输入姓名');
    }
    
    if (!bookingInfo.phone) {
        validationErrors.push('请输入电话号码');
    } else if (!/^1[3-9]\d{9}$/.test(bookingInfo.phone)) {
        validationErrors.push('请输入正确的手机号码');
    }
    
    if (!bookingInfo.email) {
        validationErrors.push('请输入邮箱');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(bookingInfo.email)) {
        validationErrors.push('请输入正确的邮箱地址');
    }
    
    if (!bookingInfo.activity) {
        validationErrors.push('请选择活动项目');
    }
    
    if (!bookingInfo.date) {
        validationErrors.push('请选择预约日期');
    }

    if (validationErrors.length > 0) {
        alert(validationErrors.join('\n'));
        return;
    }

    // 发送数据到后端
    fetch('http://localhost:8080/culture', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'userId': userId
        },
        body: JSON.stringify(bookingInfo)
    })
    .then(async response => {
        const responseText = await response.text();
        if (!response.ok) {
            console.error('服务器响应:', responseText);
            throw new Error(`请求失败 (${response.status}): ${responseText}`);
        }
        try {
            return JSON.parse(responseText);
        } catch (e) {
            console.warn('响应不是JSON格式:', responseText);
            return { message: '预约提交成功' };
        }
    })
    .then(result => {
            if(result.message === 'success'){
            alert ('预约成功！我们会尽快与您联系确认行程。');
            }
            else{
            alert(result.message);
            }
        console.log('预约结果:', result);
        document.querySelector('.booking-form').reset();
    })
    .catch(error => {
        console.error('提交失败:', error);
        alert('提交失败：' + error.message);
    });
}

// 格式化日期为 yyyy-MM-dd
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 格式化日期时间为 yyyy-MM-ddTHH:mm:ss
function formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}

// 添加日历样式
const style = document.createElement('style');
style.textContent = `
    .calendar-day {
        padding: 10px;
        text-align: center;
        border: 1px solid #eee;
    }
    
    .calendar-day.weekday {
        background-color: #f8f9fa;
        font-weight: bold;
    }
    
    .calendar-day.empty {
        background-color: #f8f9fa;
    }
    
    .calendar-day.has-event {
        background-color: #95a5a6;
        color: white;
        cursor: not-allowed;
    }
    
    .calendar-day.has-event:hover {
        background-color: #7f8c8d;
    }
`;
document.head.appendChild(style); 